package com.thinkgem.jeesite.androidpn.server.xmpp.handler;

import com.thinkgem.jeesite.androidpn.server.xmpp.UnauthorizedException;
import com.thinkgem.jeesite.androidpn.server.xmpp.session.ClientSession;
import com.thinkgem.jeesite.androidpn.server.xmpp.session.Session;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.notify.service.NotiMessageService;
import org.dom4j.Element;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

public class IQDeliverConfirmHandler extends IQHandler {
    private static final String NAMESPACE = "androidpn:iq:deliverconfirm";

    private NotiMessageService notiMessageService = SpringContextHolder.getBean(NotiMessageService.class);

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        ClientSession session = sessionManager.getSession(packet.getFrom());
        IQ reply;
        if (session == null) {
            log.error("Session not found for key " + packet.getFrom());
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            return reply;
        }
        if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
            if (IQ.Type.set.equals(packet.getType())) {
                Element element = packet.getChildElement();
                String msgId = element.elementText("pushId");
                notiMessageService.increaseAndroidSuccess(msgId);
            }
        }

        return null;
    }

    @Override
    public String getNamespace() {
        return NAMESPACE;
    }
}
